package com.tbvtc.agriculturalcreditchainserver2025.comment.iot;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

//---------------------------------------------------------------------------------------------------------//
class JsonUtil {

    public static String mapToJson(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        boolean first = true;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (!first) {
                sb.append(",");
            }
            first = false;
            sb.append("\"").append(escapeJson(entry.getKey())).append("\":")
                    .append(valueToJson(entry.getValue()));
        }
        sb.append("}");
        return sb.toString();
    }

    private static String valueToJson(Object value) {
        if (value == null) {
            return "null";
        } else if (value instanceof String) {
            return "\"" + escapeJson((String) value) + "\"";
        } else if (value instanceof Number || value instanceof Boolean) {
            return value.toString();
        } else if (value instanceof Map) {
            // 假设 Map 键均为 String 类型
            return mapToJson((Map<String, String>) value);
        } else if (value instanceof Collection) {
            return collectionToJson((Collection<?>) value);
        } else if (value.getClass().isArray()) {
            return arrayToJson(value);
        } else {
            // 其它类型调用 toString 处理，并作为字符串输出
            return "\"" + escapeJson(value.toString()) + "\"";
        }
    }

    private static String arrayToJson(Object array) {
        int length = Array.getLength(array);
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            Object element = Array.get(array, i);
            sb.append(valueToJson(element));
        }
        sb.append("]");
        return sb.toString();
    }

    private static String collectionToJson(Collection<?> collection) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        boolean first = true;
        for (Object item : collection) {
            if (!first) {
                sb.append(",");
            }
            first = false;
            sb.append(valueToJson(item));
        }
        sb.append("]");
        return sb.toString();
    }

    private static String escapeJson(String s) {
        if (s == null) {
            return null;
        }
        return s.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}
//---------------------------------------------------------------------------------------------------------//

